package com.msk.sys.utils;

import com.alibaba.fastjson2.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.msk.common.core.redis.RedisCache;
import com.msk.common.utils.StringUtils;
import com.msk.common.utils.spring.SpringUtils;
import com.msk.sys.domain.Dict;
import com.msk.sys.mapper.DictDao;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

import java.util.List;
import java.util.Map;

/**
 * @Description 马士基货运字典工具类
 * @Author zlf
 * @Date 2023/5/10 11:53
 */
public class DictMskUtils {

    private static DictDao dictDao = SpringUtils.getBean(DictDao.class);

    private static RedisCache redisService = SpringUtils.getBean(RedisCache.class);

    public static final String CACHE_DICT_MAP = "dict:dictMap";

    /**
     * 根据value获取label
     * @param value
     * @param type
     * @param defaultLabel
     * @return
     */
    public static String getDictLabel(String value, String type, String defaultLabel) {
        /**
         * 加载全部的数据
         */
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
            List<Dict> dictList = getDictList(type);
            if (CollectionUtils.isNotEmpty(dictList)) {
                for (Dict dict : dictList) {
                    if (type.equals(dict.getType()) && value.equals(dict.getValue())) {
                        return dict.getLabel();
                    }
                }
            }
        }
        return defaultLabel;
    }

    /**
     * 根据values获取labels
     * @param values
     * @param type
     * @param defaultLabels
     * @return
     */
    public static String getDictLabels(String values, String type, String defaultLabels) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)) {
            List<String> valueList = Lists.newArrayList();
            for (String value : StringUtils.split(values, ",")) {
                String dictLabel = getDictLabel(value, type, defaultLabels);
                if (StringUtils.isNotEmpty(dictLabel)) {
                    valueList.add(dictLabel);
                }
            }
            return StringUtils.join(valueList, ",");
        }
        return defaultLabels;
    }

    /**
     * 根据通用代码类型以及名称获取通用代码的值
     * @param type
     * @return
     */
    public static String[] getLabelsByType(String type){
        String[] labels = (String[]) redisService.getCacheObject(CACHE_DICT_MAP + ":" + type);
        if(labels == null || labels.length == 0){
            Dict dict = new Dict();
            dict.setType(type);
            List<Dict> lookupList =  dictDao.findList(dict);
            labels = new String[lookupList.size()];
            for (int i = 0; i < lookupList.size(); i++) {
                Dict dict2 = lookupList.get(i);
                labels[i] = dict2.getLabel();
            }
            redisService.setCacheObject(CACHE_DICT_MAP + ":" + type, labels);
        }
        return labels;
    }

    /**
     * 根据label获取value
     * @param label
     * @param type
     * @param defaultValue
     * @return
     */
    public static String getDictValue(String label, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)) {
            List<Dict> dictList = getDictList(type);
            if (CollectionUtils.isNotEmpty(dictList)) {
                for (Dict dict : dictList) {
                    if (type.equals(dict.getType()) && label.equals(dict.getLabel())) {
                        return dict.getValue();
                    }
                }
            }
        }
        return defaultValue;
    }

    /**
     * 获取只有一个配置的通用代码的值
     * @param type
     * @param defaultValue
     * @return String
     * @throws
     */
    public static String getDictValue(String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) ) {
            List<Dict> dictList = getDictListNew(type);
            if (CollectionUtils.isNotEmpty(dictList)) {
                for (Dict dict : dictList) {
                    return dict.getValue();
                }
            }
        }
        return defaultValue;
    }

    /**
     * 根据字典type获取字典项
     * @param type
     * @return
     */
    public static List<Dict> getDictList(String type) {
        @SuppressWarnings("unchecked")
        List<Dict> dictList = redisService.getCacheMapValue(CACHE_DICT_MAP, type);
        if (CollectionUtils.isEmpty(dictList)) {
            dictList = Lists.newArrayList();
        }
        return dictList;
    }

    /**
     * 清除字典key
     * @param type
     */
    public static void clearDictList(String type) {
        if (StringUtils.isNotEmpty(type)) {
            redisService.deleteCacheMapValue(CACHE_DICT_MAP, type);
        } else {
            redisService.deleteObject(CACHE_DICT_MAP);
        }
    }

    /**
     * 初始化根据字典type获取字典项
     * @param type
     * @return
     */
    public static void initNotExistDictList(String type) {
        @SuppressWarnings("unchecked")
        Dict dictQuery = new Dict();
        // 只加载有效的
        dictQuery.setValidflag("y");
        dictQuery.setType(type);
        List<Dict> dictList = dictDao.findAllList(dictQuery);
        if (CollectionUtils.isNotEmpty(dictList)) {
            Map<String, List<Dict>> dictionaryMap = Maps.newHashMap();
            for (Dict dict : dictList) {
                type = dict.getType();
                if (dictionaryMap.containsKey(type)) {
                    List<Dict> dictListSub = dictionaryMap.get(type);
                    dictListSub.add(dict);
                } else {
                    List<Dict> dictListSub = Lists.newArrayList();
                    dictListSub.add(dict);
                    dictionaryMap.put(type, dictListSub);
                }
            }
            for (String key : dictionaryMap.keySet()) {
                boolean existFlag = redisService.hasKeyCacheMap(CACHE_DICT_MAP, key);
                if (!existFlag) {
                    redisService.setCacheMapValue(CACHE_DICT_MAP, key, dictionaryMap.get(key));
                }
            }
        }
    }

    /**
     * 返回字典列表（JSON）
     * @param type
     * @return
     */
    public static String getDictListJson(String type) {
        return JsonMapper.toJsonString(getDictList(type));
    }

    /**
     * @Description 根据字典类型查询字典列表
     * @Author wlxiang
     * @Date 13:57 2023/7/3
     * @Param
     * @param dictType 字典类型
     * @return java.util.List<com.msk.sys.domain.Dict>
     **/
    public static List<Dict> getDictListNew(String dictType)
    {
        JSONArray arrayCache = redisService.getCacheMapValue(CACHE_DICT_MAP,dictType);
        if (com.msk.common.utils.StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(Dict.class);
        }
        return null;
    }

    /**
     * @Description 从字典列表中解析字典值
     * @Author wlxiang
     * @Date 11:50 2023/7/3
     * @Param 
     * @param value
     * @param dictList
     * @param defaultLabel
     * @return java.lang.String
     **/
    public static String getDictLabelNew(String value, List<Dict> dictList, String defaultLabel) {
        /**
         * 加载全部的数据
         */
        if (StringUtils.isNotBlank(value) && StringUtils.isNotEmpty( dictList)) {
            for (Dict dict : dictList) {
                if (value.equals(dict.getValue())) {
                    return dict.getLabel();
                }
            }
        }
        return defaultLabel;
    }
}
